package com.demo.transaction;

import cn.hutool.core.thread.ThreadUtil;
import com.beust.jcommander.internal.Lists;
import com.demo.transaction.domain.TestOne;
import com.demo.transaction.domain.TestT;
import com.demo.transaction.domain.User;
import com.demo.transaction.mapper.TestOneMapper;
import com.demo.transaction.mapper.TestTMapper;
import com.demo.transaction.mapper.UserMapper;
import com.demo.transaction.untils.TransactionalUntil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: lkz
 * @Title: TestController
 * @Description: TODO
 * @Date: 2023/4/27 23:17
 */
@RestController
@Slf4j
public class TestController {

    @Resource
    private UserMapper userMapper;
    @Resource
    private TestOneMapper testOneMapper;
    @Resource
    private TestTMapper testTMapper;

    private volatile  Boolean is_ok=new Boolean(true);

    @GetMapping("test")
    public List<User> getUser(){
        List<User> users = userMapper.selectList(null);
        return users;
    }

    @Resource
    private TransactionalUntil transactionalUntil;

    @GetMapping("test2")
    public void testThreadTran(){
        // 监控子线程数据
        CountDownLatch childMonitor = new CountDownLatch(2);
        // 主线程收集子线程运行最终结果
        List<Boolean> childResponse= new CopyOnWriteArrayList<>();
        //子线程在该对象上等待主线程的通知
        CountDownLatch mainMonitor = new CountDownLatch(1);

        ThreadUtil.execAsync(()->{

            // 开启事务
            TransactionStatus transactionStatus = transactionalUntil.begin();
            try {
                // 操作数据库逻辑
                List<User> user = this.getUserList();
                userMapper.insert(user.get(0));
                childResponse.add(Boolean.TRUE);
                childMonitor.countDown();

                mainMonitor.await();
                log.info("user-线程{}正常执行结束,等待其他线程执行结束",Thread.currentThread().getName());
                if(is_ok){
                    // 事务提交
                    log.info("user-线程正常执行,线程事务提交",Thread.currentThread().getName());
                    transactionalUntil.commit(transactionStatus);
                }else{
                    // 事务回滚
                    log.info("user-线程执行出现异常,线程事务回滚",Thread.currentThread().getName());
                    transactionalUntil.rollback(transactionStatus);
                }
            }catch (Exception e){
                // 提交失败
                log.info("user-线程执行出现异常{},",Thread.currentThread().getName());
                childMonitor.countDown();
                childResponse.add(Boolean.FALSE);
                transactionalUntil.rollback(transactionStatus);
            }

        });

        ThreadUtil.execAsync(()->{
            // 开启事务
            TransactionStatus transactionStatus = transactionalUntil.begin();
            try {
                // 操作数据库逻辑
                List<TestT> testTList = this.getTestTList();
                testTMapper.insert(testTList.get(0));
                log.info("test-线程{}正常执行结束,等待其他线程执行结束",Thread.currentThread().getName());
                // 模拟异常
                int a=10/0;
                childResponse.add(Boolean.TRUE);
                childMonitor.countDown();
                mainMonitor.await();
                if(is_ok){
                    // 事务提交
                    log.info("test-线程正常执行,线程事务提交",Thread.currentThread().getName());
                    transactionalUntil.commit(transactionStatus);
                }else{
                    // 事务回滚
                    log.info("test-线程执行出现异常,线程事务回滚",Thread.currentThread().getName());
                    transactionalUntil.rollback(transactionStatus);
                }
            }catch (Exception e){
                // 提交失败
                log.info("test-线程执行出现异常{},",Thread.currentThread().getName());
                childMonitor.countDown();
                childResponse.add(Boolean.FALSE);
                transactionalUntil.rollback(transactionStatus);
            }
        });

        try {
            childMonitor.await();
            for(Boolean res:childResponse){
                while (!res){
                    // 如果有一个子线程只想失败，改变mainResult状态 事务回滚
                    log.info("有线程执行失败,修改标识位,事务回滚");
                    is_ok=false;
                    break;
                }
            }
            //主线程获取结果，子线程根据主线程的结果 提交或回滚
            mainMonitor.countDown();
            System.out.println("执行结束-------");
        }catch (Exception e){
            log.info("事务执行失败");
        }

    }


    public List<User> getUserList(){
        List<User> users= Lists.newArrayList();
        for(int i=0;i<20;i++){
            User user = new User();
            user.setId(i);
            user.setUsername("小"+i);
            user.setPassword("asc");
            user.setAge(i+0);
            users.add(user);
        }
        return users;
    }

    public List<TestT> getTestTList(){
        List<TestT> TestT= Lists.newArrayList();
        for(int i=0;i<20;i++){
            TestT tt = new TestT();
            tt.setPhone("i"+"-1234537");
            tt.setId(i);
            TestT.add(tt);
        }
        return TestT;
    }
    public List<TestOne> getTestOneList(){
        List<TestOne> oneList= Lists.newArrayList();
        for(int i=0;i<20;i++){
            TestOne tt = new TestOne();
            tt.setName("i"+"-1234537");
            oneList.add(tt);
        }
        return oneList;
    }



}
